import axios from 'axios';


let instance = axios.create({
    baseURL: process.env.VUE_APP_API_URL,
    timeout: 10000,
    responseType: 'json',
});

/**
 * 请求拦截器
 */
instance.interceptors.request.use((config) => {
    //设置head
    config.headers.common['token'] = localStorage.token;
    return config;
}, function (error) {
    return Promise.reject(error);
});


/**
 * 响应拦截器
 */
instance.interceptors.response.use((res) => {
    if (res.data._status == "SUCCESS" || !res.data._status) { //接口成功
        return res;
    }
}, function (error) {
    console.error("请求不到后台服务器" + error);
    //关闭loading
    return Promise.reject(error);
});


/**
 * post请求封装方法
 * @param url
 * @param params
 * @returns {Promise}
 */
let post = function (url, params) {
    return new Promise((resolve, reject) => {
        instance.post(url, params)
        .then(response => {
            if (!response) {
                return
            }
            resolve(response.data);
        }, err => {
            reject(err);
        })
        .catch((error) => {
            reject(error)
        })
    })
};

/**
 * get请求封装方法
 * @param url
 * @param params
 * @returns {Promise}
 */
let get = function (url, params) {
    return new Promise((resolve, reject) => {
        instance.get(url, {
            params: params
        })
        .then(response => {
            if (!response) {
                return
            }
            resolve(response.data);
        }, err => {
            reject(err);
        }).catch((error) => {
            reject(error)
        })
    })
};

export default {
    get,
    post
};
